package hackathon1212;

import java.util.LinkedList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import corp.CorporateDAO;
import corp.Corporation;

import accountinfo.dao.AccountDetailsDAO;
import accountinfo.dao.Transaction;
import accountinfo.dao.TransactionsDAO;

import loyaltypartner.dao.Member;
import memberrewards.entities.AccountAdditionalInfo;
import memberrewards.entities.AccountDetail;
import memberrewards.entities.BonusOffer;
import memberrewards.entities.CatalogItem;
import memberrewards.entities.TierConfig;
import merchant.dao.Merchant;
import merchant.dao.MerchantSettlementDetail;
import merchant.dao.RecordOfCharge;
import merchant.dao.SummaryOfCharge;

public class DataDAO {

	private final List<Class> persistedClasses = new LinkedList<Class>();
	
	/*
	 * Follow the singleton pattern
	 */
	private static DataDAO singleton;
	public synchronized static DataDAO get(){
		if(singleton == null){
			singleton = new DataDAO();
		}
		return singleton;
	}
	private DataDAO(){
		init();
	}
	
	private void init() {
		persistedClasses.add(AccountAdditionalInfo.class);
		persistedClasses.add(AccountDetail.class);
		persistedClasses.add(BonusOffer.class);
		persistedClasses.add(CatalogItem.class);
		persistedClasses.add(TierConfig.class);
		persistedClasses.add(Merchant.class);
		persistedClasses.add(MerchantSettlementDetail.class);
		persistedClasses.add(RecordOfCharge.class);
		persistedClasses.add(SummaryOfCharge.class);
		persistedClasses.add(Member.class);
		persistedClasses.add(Transaction.class);
	}

	
	
	public String getData(){
		
		
		
		
		return getJPAData() + getMapData();
	}
	private String getJPAData() {
		final StringBuilder sb = new StringBuilder();
		
		final EntityManager em = EMF.get().createEntityManager();
		try{
			for(final Class c : persistedClasses){
				final Query q = em.createQuery("SELECT obj from " + c.getName() + " obj");
				sb.append("<h1>" + c.getName() +  "</h1><br>");
				for(final Object o : q.getResultList()){
					sb.append(GsonFactory.get().toJson(o));
					sb.append("<br>");
				}
			}
			

		} finally {
			em.close();
		}		
		return sb.toString();
	}
	private String getMapData() {
		final StringBuilder sb = new StringBuilder();
		sb.append("<h1>" + accountinfo.dao.AccountDetail.class.getName() +  "</h1><br>");
		sb.append(GsonFactory.get().toJson(AccountDetailsDAO.cardAccounts));
		
		sb.append("<h1>" + Corporation.class.getName() +  "</h1><br>");
		sb.append(GsonFactory.get().toJson(CorporateDAO.getInstance().corporations));	
		
		return sb.toString();
	}
	
}
